<template>
    <div class="app-container">
        <el-form :inline="true" ref="queryRef" label-position="right" :model="params" label-width="200px">
            <div class="form-inline">
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="维护人：" class="form-item" prop="userName">
                            <el-input v-model="params.userName" placeholder="" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="维护时间:">
                            <el-col :span="11">
                                <el-form-item prop="createStartTime">
                                    <el-date-picker clearable v-model="params.createStartTime" type="date"
                                        placeholder="开始时间" value-format="YYYY-MM-DD" :disabled-date="startDisableDate"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="1" class="text-center">
                                <span class="text-gray-500">-</span>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item prop="createEndTime">
                                    <el-date-picker clearable v-model="params.createEndTime" type="date" placeholder="结束时间"
                                        value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="年代：" class="form-item" prop="years">
                            <el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
                                <el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="设防情况：" class="form-item" prop="fortification">
                            <el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
                                <el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="重大工程类别：" class="form-item" prop="majorProjectCategory">
                            <el-select v-model="params.majorProjectCategory" placeholder="请选择" class="form-select"
                                clearable>
                                <el-option v-for="item in majorProjectCategoryOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11"></el-col>
                </el-row>
                <el-row justify="end">
                    <el-form-item class="bottom-button">
                        <el-button type="primary" @click="onModify">修改</el-button>
                        <el-button type="primary" @click="onDelete">删除</el-button>
                        <el-button type="primary" @click="importParmsClick()">导入</el-button>
                        <el-button type="primary" @click="onSearch">查询</el-button>
                        <el-button type="primary" @click="onRest">重置</el-button>
                    </el-form-item>
                </el-row>
            </div>
        </el-form>

        <div class="table-wrapper">
            <el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
                @selection-change="handleSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
                :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                <el-table-column type="selection" width="55" label="序号" />
                <el-table-column prop="cipvCode" header-align="center" align="center" label="编号">
                    <template #default="scope">
                        <el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">
                            {{ scope.row.cipvCode }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="years" header-align="center" align="center" label="年代" />
                <el-table-column prop="fortification" header-align="center" align="center" label="设防情况" />
                <el-table-column prop="userName" header-align="center" align="center" label="维护人" />
                <el-table-column prop="createTime" header-align="center" align="center" label="维护时间" />
                <!-- <el-table-column prop="businessObject" header-align="center" align="center" label="烈度" />
                                <el-table-column prop="sod" header-align="center" align="center" label="破坏状态" /> -->
                <el-table-column prop="majorProjectCategory" header-align="center" align="center" label="重大工程类别" />
            </el-table>
            <div class="paging">
                <el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
                    :page-size="queryPagination.pageSize" :total="queryPagination.total"
                    @current-change="handleCurrentChange" @size-change="handleSizeChange" />
            </div>
        </div>

        <el-dialog v-model="dialogVisible" title="导入数据" width="30%">
            <div class="downloadModel">
                <!-- 下载导入模板{{ downloadInfo.fileName }} -->
                下载导入模板<span @click="importTemplate">{{ downloadFileName }}</span>
            </div>
            <el-upload ref="uploadRef" :action="uploadFileUrl" :before-upload="beforeUpload" :before-remove="beforeRemove"
                :on-success="uploadSuccess" :on-error="uploadError" :file-list.sync="fileList" :headers="headers"
                :data="uploadParams" :multiple="false" :limit="1" :auto-upload="false">
                <el-button type="primary" class="icon-Angle-upload"> 选择本地文件</el-button>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button size="default" @click="cancleUpload">取 消</el-button>
                    <el-button size="default" type="primary" @click="submitUpload">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
// 引入接口
import { getToken } from "@/utils/auth";
import {
    importMajorProjectsData,
    importNpsData,
    queryCipVulnerability,
    deleteDataByNumber,
} from "@/api/majorEnginVulnerAnalysis/majorEnginVulnerAnalysis.js";
// 引入store
import useDictStore from '@/store/modules/dict';
import { number } from "echarts/lib/export";
// 获取pinia
const dictStore = useDictStore();

// 当前实例
const { proxy } = getCurrentInstance();
// 接口根路径
const baseURL = import.meta.env.VITE_APP_BASE_API;
const headers = ref({ token: "token " + getToken() });
// 全局路由对象
const router = useRouter();

// 数据导入
const uploadRef = ref()
const dialogVisible = ref(false)
// 取消上传
const cancleUpload = (res) => {
    dialogVisible.value = false
}
// 提交上传
const submitUpload = (res) => {
    uploadRef.value.submit()
}
// 上传地址
const uploadFileUrl = ref(baseURL + "/importData/importMajorProjectsData");
// 文件列表
const fileList = ref([]);
// 上传参数设置
const uploadParams = ref({ type: '' });
// 模板名称
const downloadFileName = ref('输油输气管线易损性导入模板.xlsx');
const importParmsClick = (val) => {
    if (params.value.majorProjectCategory == "") {
        proxy.$modal.msgWarning("请选择重大工程类别");
        return;
    }
    fileList.value = [];
    uploadParams.value.type = params.value.majorProjectCategory
    switch (params.value.majorProjectCategory) {
        case '输油管线':
            dialogVisible.value = true
            downloadFileName.value = '输油输气管线易损性导入模板.xlsx'
            uploadFileUrl.value = baseURL + "/importData/importMajorProjectsData"
            break;
        case '输气管线':
            dialogVisible.value = true
            downloadFileName.value = '输油输气管线易损性导入模板.xlsx'
            uploadFileUrl.value = baseURL + "/importData/importMajorProjectsData"
            break;
        case '核电站':
            dialogVisible.value = true
            downloadFileName.value = '核电站易损性导入模板.xlsx'
            uploadFileUrl.value = baseURL + "/importData/importNpsData"
            break;
        case '水库大坝':
            dialogVisible.value = true
            downloadFileName.value = '水库大坝易损性导入模板.xlsx'
            uploadFileUrl.value = baseURL + "/importData/importMajorProjectsData"
            break;
        case '其他重大工程设施':
            dialogVisible.value = true
            downloadFileName.value = '其他重大工程设施易损性导入模板.xlsx'
            uploadFileUrl.value = baseURL + "/importData/importMajorProjectsData"
            break;
        default:
            break;
    }
}
// 模板下载
function importTemplate() {
    proxy.download("/base/product/downloadExcel", {
        fileName: downloadFileName.value
    }, downloadFileName.value);
};
//文件上传
const beforeRemove = () => {
    fileList.value = [];
};
// 上传前回调
const beforeUpload = (file) => {
    const fileSize = file.size / 1024 / 1024;
    if (fileSize > 200) {
        $message.error('文件大小不能超过200M!');
        return false;
    }
    const fileReg = /.xls|.xlsx/;
    if (!fileReg.test(file.name)) {
        $message.error('请选择.xls .xlsx格式文件');
        return false;
    }
    return true;
};
// 上传完成回调
const uploadSuccess = (response, uploadFile, uploadFiles) => {
    if (response.code === 200) {
        proxy.$modal.msgSuccess("上传文件成功");
        dialogVisible.value = false
        onSearch()
    } else {
        proxy.$modal.msgError(response.message || "导入失败，请检查表头是否改动");
    }
}
// 上传失败回调
const uploadError = (response, uploadFile, uploadFiles) => {
    proxy.$modal.msgError(response.message || "导入失败，请检查表头是否改动");
}

const data = reactive({
    // 表单参数
    params: {
        createStartTime: "", //维护开始时间
        createEndTime: "",//维护结束时间
        userName: "", //维护人
        fortification: "", //设防情况
        years: "",//年代
        majorProjectCategory: "",//重大工程类别
    },
    // 设防情况
    fortificationOptions: dictStore.fortificationOptions || [],
    // 年份
    yearsOptions: dictStore.yearsOptions2 || [],
    // 重大工程类别
    majorProjectCategoryOptions: dictStore.majorProjectCategoryOptions || [],
    //表格
    tableData: [],
    //分页
    layout: " prev, pager, next, jumper, sizes, total",
    queryPagination: {
        pageNo: 1,
        pageSize: 10,
        total: 100,
    },
})
const {
    params,
    fortificationOptions,
    yearsOptions,
    majorProjectCategoryOptions,
    tableData,
    queryPagination,
    layout
} = toRefs(data);

// 开始、结束时间可选区间控制
const startDisableDate = (time) => {
    let endDateVal = params.value.createEndTime
    if (endDateVal) {
        return time.getTime() > new Date(endDateVal).getTime()
    }
}
const endDisableDate = (time) => {
    let beginDateVal = params.value.createStartTime
    if (beginDateVal) {
        return time.getTime() < new Date(beginDateVal).getTime()
    }
}

//表格
const multipleTableRef = ref();
// 表格多选列表
const multipleSelection = ref();
// 表格选择事件
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 分页，每页显示条数
const handleSizeChange = (val) => {
    // 改变每页显示的条数
    queryPagination.value.pageSize = val;
    // 注意：在改变每页显示的条数时，要将页码显示到第一页
    queryPagination.value.pageNo = 1;
    onSearch();
};
// 分页，当前页数
const handleCurrentChange = (val) => {
    queryPagination.value.pageNo = val;
    onSearch();
};

// 点击编号跳转
const viewProject = (row) => {
    if (row.majorProjectCategory == '输油管线') {
        router.push({
            path: '/majorEnginVulnerAnalysis/pipelineVulnerManagement', query: {
                cipvCode: row.cipvCode
            }
        })
    } else if (row.majorProjectCategory == '输气管线') {
        router.push({
            path: '/majorEnginVulnerAnalysis/pipelineVulnerManagement', query: {
                cipvCode: row.cipvCode
            }
        })
    } else if (row.majorProjectCategory == '核电站') {
        router.push({
            path: '/majorEnginVulnerAnalysis/nuclearPowerVulnerManagement', query: {
                cipvCode: row.cipvCode
            }
        })
    } else if (row.majorProjectCategory == '水库大坝') {
        router.push({
            path: '/majorEnginVulnerAnalysis/reservoirDamVulnerManagement', query: {
                cipvCode: row.cipvCode
            }
        })
    } else if (row.majorProjectCategory == '其他重大工程设施') {
        router.push({
            path: '/majorEnginVulnerAnalysis/otherMajorVulnerManagement', query: {
                cipvCode: row.cipvCode
            }
        })
    }
}
//修改跳转
const onModify = () => {
    if (multipleSelection.value && multipleSelection.value.length > 1) {
        proxy.$modal.msgWarning("请只选择一行数据进行修改！");
    } else if (multipleSelection.value && multipleSelection.value.length == 1) {
        viewProject(multipleSelection.value[0]);
    } else {
        proxy.$modal.msgWarning("请选择数据行！");
    }
}
// 删除行
const onDelete = () => {
    const ids = []
    if (!multipleSelection.value || multipleSelection.value.length <= 0) {
        ElMessage({
            type: 'warning',
            message: '请选中数据!'
        });
        return
    }
    multipleSelection.value.forEach(item => {
        ids.push(item.cipvCode)
    })
    const paramsp = { numbers: ids.join(",") }
    deleteDataByNumber(paramsp).then((res) => {
        console.log(res)
        if (res.code === 200) {
            console.log(res)
            ElMessage({
                type: 'success',
                message: '删除成功!'
            });
            onSearch();
        }
    }).catch(err => {
        ElMessage({
            type: 'error',
            message: '删除失败!'
        });
    })
}

//查询，重大工程设施易损性分析
const onSearch = () => {
    const query = {
        ...params.value,
        page: queryPagination.value.pageNo,
        rows: queryPagination.value.pageSize
    }
    queryCipVulnerability(query).then((res) => {
        const rows = res.data.rows;
        if (res.code === 200 && rows) {
            queryPagination.value.total = res.data.total
            tableData.value = [];
            //循环遍历之前加上非空判断
            if (rows.length) {
                tableData.value = [ ...rows ];
            }
        }
    }).catch(err => {
        console.log(err);
    });
};
//重置
const onRest = () => {
    proxy.resetForm("queryRef")
    queryPagination.value.pageNo = 1;
    onSearch();
};

// 挂载
onMounted(() => {
    // 查询
    onSearch();
});
</script>

<style lang="scss" scoped>
.paging {
    padding: 20px 0;
}

.form-inline {
    .el-form-item {
        margin-right: 0px;
    }
}

.downloadModel {
    font-size: 16px;
    line-height: 60px;

    span {
        color: #107ce5;
        cursor: pointer;
    }
}
</style>
